"""
数据加载器

负责从Excel文件加载项目数据，支持三个主要数据表：
1. project_info - 项目基本信息
2. project_roles - 项目角色需求
3. phases_detail - 阶段详细信息
"""

import pandas as pd
import openpyxl
from typing import List, Dict, Any, Optional, Tuple
from pathlib import Path
import logging
from datetime import datetime

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from models.data_models import ProjectInfo, ProjectRole, PhaseDetail, ValidationResult
    from models.project import Project
    from models.resource import Resource
    from models.task import Task
except ImportError:
    # 如果直接导入不成功，使用简单的数据类
    from typing import NamedTuple
    
    class ProjectInfo(NamedTuple):
        project_id: str
        project_name: str
        start_date: str
        end_date: str
        priority: str
        
    class ProjectRole(NamedTuple):
        role: str
        required_people: int
        skills: str
        
    class PhaseDetail(NamedTuple):
        phase_name: str
        start_date: str
        end_date: str
        work_hours: float
        
    class ValidationResult(NamedTuple):
        is_valid: bool
        errors: list
        warnings: list
        
    class Project:
        def __init__(self, project_id, project_name, start_date=None, end_date=None, priority=1, description=""):
            self.project_id = project_id
            self.project_name = project_name
            self.start_date = start_date
            self.end_date = end_date
            self.priority = priority
            self.description = description
            
    class Resource:
        def __init__(self, resource_id, name, department="", skills=None, availability=1.0, cost_per_hour=0.0, **kwargs):
            self.resource_id = resource_id
            self.name = name
            self.department = department
            self.skills = skills or {}
            self.availability = availability
            self.cost_per_hour = cost_per_hour
            # 支持其他参数
            for key, value in kwargs.items():
                setattr(self, key, value)
            
    class Task:
        def __init__(self, task_id, project_id, task_name, estimated_hours=0, start_date=None, end_date=None, required_skills=None, priority=1, **kwargs):
            self.task_id = task_id
            self.project_id = project_id
            self.task_name = task_name
            self.estimated_hours = estimated_hours
            self.start_date = start_date
            self.end_date = end_date
            self.required_skills = required_skills or []
            self.priority = priority
            # 支持其他参数
            for key, value in kwargs.items():
                setattr(self, key, value)


class DataLoader:
    """
    数据加载器类
    
    专门用于从Excel文件加载项目资源规划数据，支持多工作表结构。
    """
    
    def __init__(self):
        """初始化数据加载器"""
        self.logger = logging.getLogger(__name__)
        
        # 预定义的工作表名称
        self.sheet_names = {
            'project_info': 'project_info',
            'project_roles': 'project_roles', 
            'phases_detail': 'phases_detail'
        }
        
        # 预定义的列名映射（支持中英文列名）
        self.column_mappings = {
            'project_info': {
                'project_code': ['project_code', '项目代码', '项目编号'],
                'project_name': ['project_name', '项目名称', '项目名'],
                'start_month': ['start_month', '开始月份', '开始时间'],
                'end_month': ['end_month', '结束月份', '结束时间'],
                'priority': ['priority', '优先级', '项目优先级'],
                'description': ['description', '项目描述', '描述', '备注']
            },
            'project_roles': {
                'project_code': ['project_code', '项目代码', '项目编号'],
                'role_name': ['role_name', '角色名称', '角色'],
                'required_count': ['required_count', '需要人数', '人数'],
                'skill_requirements': ['skill_requirements', '技能要求', '技能'],
                'experience_level': ['experience_level', '经验等级', '经验要求'],
                'work_ratio': ['work_ratio', '工作占比', '占比']
            },
            'phases_detail': {
                'project_code': ['project_code', '项目代码', '项目编号'],
                'phase_name': ['phase_name', '阶段名称', '阶段'],
                'start_month': ['start_month', '开始月份', '开始时间'],
                'end_month': ['end_month', '结束月份', '结束时间'],
                'dependencies': ['dependencies', '依赖阶段', '前置阶段'],
                'deliverables': ['deliverables', '交付物', '输出']
            }
        }
    
    def load_from_excel(self, file_path: str) -> Dict[str, List]:
        """
        从Excel文件加载所有数据
        
        Args:
            file_path (str): Excel文件路径
            
        Returns:
            Dict[str, List]: 包含所有数据的字典 {
                'projects': List[ProjectInfo],
                'project_roles': List[ProjectRole], 
                'phases': List[PhaseDetail],
                'validation': ValidationResult
            }
            
        Raises:
            FileNotFoundError: 文件不存在
            ValueError: 数据格式错误
        """
        try:
            self.logger.info(f"开始加载Excel文件: {file_path}")
            
            # 检查文件是否存在
            if not Path(file_path).exists():
                raise FileNotFoundError(f"Excel文件不存在: {file_path}")
            
            # 加载Excel工作簿
            workbook = openpyxl.load_workbook(file_path, read_only=True)
            
            # 检查必要的工作表是否存在
            validation_result = self._validate_workbook_structure(workbook)
            
            if validation_result.has_errors():
                self.logger.error(f"工作簿结构验证失败: {validation_result.get_summary()}")
                return {
                    'projects': [],
                    'project_roles': [],
                    'phases': [],
                    'validation': validation_result
                }
            
            # 加载各个工作表的数据
            projects = self._load_project_info(file_path)
            project_roles = self._load_project_roles(file_path)
            phases = self._load_phases_detail(file_path)
            
            # 进行数据完整性验证
            data_validation = self._validate_data_integrity(projects, project_roles, phases)
            
            # 合并验证结果
            validation_result.warnings.extend(data_validation.warnings)
            validation_result.errors.extend(data_validation.errors)
            validation_result.suggestions.extend(data_validation.suggestions)
            
            if data_validation.has_errors():
                validation_result.is_valid = False
            
            result = {
                'projects': projects,
                'project_roles': project_roles,
                'phases': phases,
                'validation': validation_result
            }
            
            self.logger.info(f"数据加载完成: {len(projects)}个项目, {len(project_roles)}个角色, {len(phases)}个阶段")
            return result
            
        except Exception as e:
            self.logger.error(f"加载Excel文件失败: {e}")
            raise
    
    def _validate_workbook_structure(self, workbook: openpyxl.Workbook) -> ValidationResult:
        """
        验证工作簿结构
        
        Args:
            workbook: Excel工作簿对象
            
        Returns:
            ValidationResult: 验证结果
        """
        validation = ValidationResult(is_valid=True)
        available_sheets = workbook.sheetnames
        
        # 检查必要的工作表
        for sheet_type, expected_name in self.sheet_names.items():
            if expected_name not in available_sheets:
                # 尝试查找类似名称的工作表
                similar_sheets = [s for s in available_sheets if expected_name.lower() in s.lower()]
                if similar_sheets:
                    validation.add_warning(
                        f"未找到工作表 '{expected_name}'，但发现类似的工作表: {similar_sheets}。"
                        f"请确认工作表名称是否正确。"
                    )
                else:
                    validation.add_error(f"缺少必要的工作表: {expected_name}")
        
        return validation
    
    def _load_project_info(self, file_path: str) -> List[ProjectInfo]:
        """
        加载项目基本信息
        
        Args:
            file_path (str): Excel文件路径
            
        Returns:
            List[ProjectInfo]: 项目信息列表
        """
        try:
            df = pd.read_excel(file_path, sheet_name=self.sheet_names['project_info'])
            projects = []
            
            # 标准化列名
            df = self._normalize_columns(df, 'project_info')
            
            for index, row in df.iterrows():
                try:
                    # 处理月份格式
                    start_month = self._format_month(row.get('start_month'))
                    end_month = self._format_month(row.get('end_month'))
                    
                    project = ProjectInfo(
                        project_code=str(row['project_code']).strip(),
                        project_name=str(row['project_name']).strip(),
                        start_month=start_month,
                        end_month=end_month,
                        priority=int(row.get('priority', 1)),
                        description=str(row.get('description', '')).strip()
                    )
                    
                    # 验证项目数据
                    if project.validate():
                        projects.append(project)
                    else:
                        self.logger.warning(f"跳过无效的项目数据行 {index + 2}: {project.project_code}")
                        
                except Exception as e:
                    self.logger.warning(f"跳过项目信息行 {index + 2}: {e}")
                    continue
            
            self.logger.info(f"成功加载 {len(projects)} 个项目信息")
            return projects
            
        except Exception as e:
            self.logger.error(f"加载项目信息失败: {e}")
            return []
    
    def _load_project_roles(self, file_path: str) -> List[ProjectRole]:
        """
        加载项目角色需求
        
        Args:
            file_path (str): Excel文件路径
            
        Returns:
            List[ProjectRole]: 项目角色列表
        """
        try:
            df = pd.read_excel(file_path, sheet_name=self.sheet_names['project_roles'])
            project_roles = []
            
            # 标准化列名
            df = self._normalize_columns(df, 'project_roles')
            
            for index, row in df.iterrows():
                try:
                    # 处理技能要求
                    skill_requirements = self._parse_list_field(row.get('skill_requirements', ''))
                    
                    project_role = ProjectRole(
                        project_code=str(row['project_code']).strip(),
                        role_name=str(row['role_name']).strip(),
                        required_count=int(row.get('required_count', 1)),
                        skill_requirements=skill_requirements,
                        experience_level=str(row.get('experience_level', '中级')).strip(),
                        work_ratio=float(row.get('work_ratio', 1.0))
                    )
                    
                    # 验证角色数据
                    if project_role.validate():
                        project_roles.append(project_role)
                    else:
                        self.logger.warning(f"跳过无效的角色数据行 {index + 2}: {project_role.project_code}-{project_role.role_name}")
                        
                except Exception as e:
                    self.logger.warning(f"跳过项目角色行 {index + 2}: {e}")
                    continue
            
            self.logger.info(f"成功加载 {len(project_roles)} 个项目角色")
            return project_roles
            
        except Exception as e:
            self.logger.error(f"加载项目角色失败: {e}")
            return []
    
    def _load_phases_detail(self, file_path: str) -> List[PhaseDetail]:
        """
        加载阶段详细信息
        
        Args:
            file_path (str): Excel文件路径
            
        Returns:
            List[PhaseDetail]: 阶段详细信息列表
        """
        try:
            df = pd.read_excel(file_path, sheet_name=self.sheet_names['phases_detail'])
            phases = []
            
            # 标准化列名
            df = self._normalize_columns(df, 'phases_detail')
            
            for index, row in df.iterrows():
                try:
                    # 处理月份格式
                    start_month = self._format_month(row.get('start_month'))
                    end_month = self._format_month(row.get('end_month'))
                    
                    # 处理依赖关系和交付物
                    dependencies = self._parse_list_field(row.get('dependencies', ''))
                    deliverables = self._parse_list_field(row.get('deliverables', ''))
                    
                    # 处理角色分配（从动态列中提取）
                    role_allocations = self._extract_role_allocations(row, df.columns)
                    
                    phase = PhaseDetail(
                        project_code=str(row['project_code']).strip(),
                        phase_name=str(row['phase_name']).strip(),
                        start_month=start_month,
                        end_month=end_month,
                        role_allocations=role_allocations,
                        dependencies=dependencies,
                        deliverables=deliverables
                    )
                    
                    # 验证阶段数据
                    if phase.validate():
                        phases.append(phase)
                    else:
                        self.logger.warning(f"跳过无效的阶段数据行 {index + 2}: {phase.project_code}-{phase.phase_name}")
                        
                except Exception as e:
                    self.logger.warning(f"跳过阶段详情行 {index + 2}: {e}")
                    continue
            
            self.logger.info(f"成功加载 {len(phases)} 个阶段详情")
            return phases
            
        except Exception as e:
            self.logger.error(f"加载阶段详情失败: {e}")
            return []
    
    def _normalize_columns(self, df: pd.DataFrame, sheet_type: str) -> pd.DataFrame:
        """
        标准化DataFrame的列名
        
        Args:
            df (pd.DataFrame): 原始DataFrame
            sheet_type (str): 工作表类型
            
        Returns:
            pd.DataFrame: 标准化后的DataFrame
        """
        if sheet_type not in self.column_mappings:
            return df
        
        column_mapping = self.column_mappings[sheet_type]
        rename_dict = {}
        
        for standard_name, possible_names in column_mapping.items():
            for col in df.columns:
                if str(col).strip() in possible_names:
                    rename_dict[col] = standard_name
                    break
        
        return df.rename(columns=rename_dict)
    
    def _format_month(self, month_value: Any) -> str:
        """
        格式化月份值为标准格式 YYYY-MM
        
        Args:
            month_value: 月份值（可能是字符串、日期或数字）
            
        Returns:
            str: 格式化后的月份字符串
        """
        if pd.isna(month_value):
            return ""
        
        month_str = str(month_value).strip()
        
        # 如果已经是YYYY-MM格式
        if len(month_str) == 7 and month_str[4] == '-':
            return month_str
        
        # 尝试解析为日期
        try:
            if isinstance(month_value, datetime):
                return month_value.strftime('%Y-%m')
            
            # 尝试pandas日期解析
            date_obj = pd.to_datetime(month_value)
            return date_obj.strftime('%Y-%m')
            
        except Exception:
            # 如果解析失败，尝试其他格式
            try:
                # 处理YYYYMM格式
                if len(month_str) == 6 and month_str.isdigit():
                    year = month_str[:4]
                    month = month_str[4:6]
                    return f"{year}-{month}"
                
                # 处理YYYY/MM格式
                if '/' in month_str:
                    parts = month_str.split('/')
                    if len(parts) == 2:
                        year, month = parts
                        return f"{year.zfill(4)}-{month.zfill(2)}"
                
            except Exception:
                pass
        
        self.logger.warning(f"无法解析月份格式: {month_value}")
        return str(month_value)
    
    def _parse_list_field(self, field_value: Any) -> List[str]:
        """
        解析列表字段（用逗号分隔的字符串）
        
        Args:
            field_value: 字段值
            
        Returns:
            List[str]: 解析后的字符串列表
        """
        if pd.isna(field_value) or not field_value:
            return []
        
        field_str = str(field_value).strip()
        if not field_str:
            return []
        
        # 按逗号分割并清理空白
        items = [item.strip() for item in field_str.split(',')]
        return [item for item in items if item]
    
    def _extract_role_allocations(self, row: pd.Series, columns: pd.Index) -> Dict[str, int]:
        """
        从行数据中提取角色分配信息
        
        Args:
            row (pd.Series): 数据行
            columns (pd.Index): 列名索引
            
        Returns:
            Dict[str, int]: 角色分配字典 {role_name: count}
        """
        role_allocations = {}
        
        # 预定义的基础列名（不是角色列）
        basic_columns = {
            'project_code', 'phase_name', 'start_month', 'end_month',
            'dependencies', 'deliverables', '项目代码', '阶段名称', 
            '开始月份', '结束月份', '依赖阶段', '交付物'
        }
        
        # 查找角色列（不在基础列中的列被认为是角色列）
        for col in columns:
            col_name = str(col).strip()
            if col_name not in basic_columns and not pd.isna(row[col]):
                try:
                    count = int(float(row[col]))  # 先转float再转int，处理可能的小数格式
                    if count > 0:
                        role_allocations[col_name] = count
                except (ValueError, TypeError):
                    # 如果不能转换为数字，跳过这一列
                    continue
        
        return role_allocations
    
    def _validate_data_integrity(
        self, 
        projects: List[ProjectInfo], 
        project_roles: List[ProjectRole], 
        phases: List[PhaseDetail]
    ) -> ValidationResult:
        """
        验证数据完整性和一致性
        
        Args:
            projects: 项目信息列表
            project_roles: 项目角色列表
            phases: 阶段详细信息列表
            
        Returns:
            ValidationResult: 验证结果
        """
        validation = ValidationResult(is_valid=True)
        
        if not projects:
            validation.add_error("未加载到任何项目信息")
            return validation
        
        # 构建项目代码集合
        project_codes = {p.project_code for p in projects}
        
        # 验证项目角色的项目代码引用
        role_project_codes = {r.project_code for r in project_roles}
        orphan_role_projects = role_project_codes - project_codes
        if orphan_role_projects:
            validation.add_warning(f"以下项目的角色信息没有对应的项目基础信息: {orphan_role_projects}")
        
        # 验证阶段的项目代码引用
        phase_project_codes = {p.project_code for p in phases}
        orphan_phase_projects = phase_project_codes - project_codes
        if orphan_phase_projects:
            validation.add_warning(f"以下项目的阶段信息没有对应的项目基础信息: {orphan_phase_projects}")
        
        # 验证阶段的角色分配与项目角色的一致性
        for phase in phases:
            project_role_names = {
                r.role_name for r in project_roles 
                if r.project_code == phase.project_code
            }
            
            phase_role_names = set(phase.role_allocations.keys())
            
            # 检查阶段中使用的角色是否在项目角色中定义
            undefined_roles = phase_role_names - project_role_names
            if undefined_roles:
                validation.add_warning(
                    f"项目 {phase.project_code} 阶段 {phase.phase_name} 中使用了未定义的角色: {undefined_roles}"
                )
        
        # 验证项目时间范围与阶段时间的一致性
        for project in projects:
            project_phases = [p for p in phases if p.project_code == project.project_code]
            
            if project_phases:
                phase_start_months = [p.start_month for p in project_phases]
                phase_end_months = [p.end_month for p in project_phases]
                
                earliest_phase = min(phase_start_months)
                latest_phase = max(phase_end_months)
                
                if earliest_phase < project.start_month:
                    validation.add_warning(
                        f"项目 {project.project_code} 的阶段开始时间 {earliest_phase} "
                        f"早于项目开始时间 {project.start_month}"
                    )
                
                if latest_phase > project.end_month:
                    validation.add_warning(
                        f"项目 {project.project_code} 的阶段结束时间 {latest_phase} "
                        f"晚于项目结束时间 {project.end_month}"
                    )
        
        # 检查缺少某些常见角色的情况
        self._check_missing_common_roles(projects, project_roles, validation)
        
        return validation
    
    def _check_missing_common_roles(
        self, 
        projects: List[ProjectInfo], 
        project_roles: List[ProjectRole], 
        validation: ValidationResult
    ) -> None:
        """
        检查项目是否缺少常见角色
        
        Args:
            projects: 项目列表
            project_roles: 项目角色列表
            validation: 验证结果对象
        """
        # 常见的必要角色
        common_roles = {
            '项目经理', 'PM', 'TL', '技术负责人',
            '前端开发工程师', '后端开发工程师', '全栈开发工程师'
        }
        
        for project in projects:
            project_role_names = {
                r.role_name for r in project_roles 
                if r.project_code == project.project_code
            }
            
            # 检查是否有管理角色
            management_roles = {'项目经理', 'PM', 'TL', '技术负责人'}
            has_management = bool(management_roles & project_role_names)
            
            if not has_management:
                validation.add_suggestion(
                    f"项目 {project.project_code} 建议添加管理角色（如：项目经理、TL、技术负责人）"
                )
            
            # 检查是否有开发角色
            developer_roles = {'前端开发工程师', '后端开发工程师', '全栈开发工程师', '开发工程师'}
            has_developer = bool(developer_roles & project_role_names)
            
            if not has_developer:
                validation.add_warning(
                    f"项目 {project.project_code} 没有定义开发角色，请确认是否正确"
                )
    
    def load_all_data(self, projects_file: str, resources_file: str, tasks_file: str) -> Dict[str, List]:
        """
        加载所有数据文件
        
        Args:
            projects_file: 项目数据文件路径
            resources_file: 资源数据文件路径
            tasks_file: 任务数据文件路径
            
        Returns:
            Dict[str, List]: 包含项目、资源和任务数据的字典
        """
        try:
            self.logger.info("开始加载数据文件...")
            
            # 加载项目数据
            projects = self._load_projects_from_excel(projects_file)
            
            # 加载资源数据
            resources = self._load_resources_from_excel(resources_file)
            
            # 加载任务数据
            tasks = self._load_tasks_from_excel(tasks_file)
            
            self.logger.info(f"数据加载完成: {len(projects)}个项目, {len(resources)}个资源, {len(tasks)}个任务")
            
            return {
                'projects': projects,
                'resources': resources,
                'tasks': tasks
            }
            
        except Exception as e:
            self.logger.error(f"数据加载失败: {e}")
            raise
    
    def _load_projects_from_excel(self, file_path: str) -> List[Project]:
        """从 Excel 文件加载项目数据"""
        try:
            df = pd.read_excel(file_path)
            projects = []
            
            for index, row in df.iterrows():
                try:
                    # 安全地获取优先级值
                    priority_val = row.get('优先级', row.get('priority', 1))
                    try:
                        priority = int(priority_val) if pd.notna(priority_val) else 1
                    except (ValueError, TypeError):
                        priority = 1
                    
                    project = Project(
                        project_id=str(row.get('项目编号', row.get('project_id', f'PRJ{index:03d}'))).strip(),
                        project_name=str(row.get('项目名称', row.get('project_name', f'项目{index}'))).strip(),
                        start_date=row.get('开始日期', row.get('start_date')),
                        end_date=row.get('结束日期', row.get('end_date')),
                        priority=priority,
                        description=str(row.get('项目描述', row.get('description', ''))).strip()
                    )
                    projects.append(project)
                except Exception as e:
                    self.logger.warning(f"跳过项目数据行 {index + 2}: {e}")
                    continue
            
            return projects
            
        except Exception as e:
            self.logger.error(f"加载项目数据失败: {e}")
            return []
    
    def _load_resources_from_excel(self, file_path: str) -> List[Resource]:
        """从 Excel 文件加载资源数据"""
        try:
            df = pd.read_excel(file_path)
            resources = []
            
            for index, row in df.iterrows():
                try:
                    # 处理技能数据
                    skills = {}
                    for col in df.columns:
                        if '技能' in str(col) and col != '技能描述':
                            skill_level = row.get(col)
                            if pd.notna(skill_level) and skill_level > 0:
                                skill_name = str(col).replace('技能_', '').replace('技能', '')
                                skills[skill_name] = float(skill_level)
                    
                    # 安全地获取数值
                    try:
                        availability = float(row.get('可用性', row.get('availability', 1.0)))
                    except (ValueError, TypeError):
                        availability = 1.0
                    
                    try:
                        cost_per_hour = float(row.get('小时成本', row.get('cost_per_hour', 0.0)))
                    except (ValueError, TypeError):
                        cost_per_hour = 0.0
                    
                    resource = Resource(
                        resource_id=str(row.get('员工编号', row.get('resource_id', f'RES{index:03d}'))).strip(),
                        name=str(row.get('姓名', row.get('name', f'员工{index}'))).strip(),
                        department=str(row.get('部门', row.get('department', ''))).strip(),
                        skills=skills,
                        availability=availability,
                        cost_per_hour=cost_per_hour
                    )
                    resources.append(resource)
                except Exception as e:
                    self.logger.warning(f"跳过资源数据行 {index + 2}: {e}")
                    continue
            
            return resources
            
        except Exception as e:
            self.logger.error(f"加载资源数据失败: {e}")
            return []
    
    def _load_tasks_from_excel(self, file_path: str) -> List[Task]:
        """从 Excel 文件加载任务数据"""
        try:
            df = pd.read_excel(file_path)
            tasks = []
            
            for index, row in df.iterrows():
                try:
                    # 处理技能需求
                    required_skills = []
                    skill_desc = row.get('技能需求', row.get('required_skills', ''))
                    if pd.notna(skill_desc) and skill_desc:
                        required_skills = [s.strip() for s in str(skill_desc).split(',') if s.strip()]
                    
                    # 安全地获取数值
                    try:
                        estimated_hours = float(row.get('预估小时', row.get('estimated_hours', 40)))
                    except (ValueError, TypeError):
                        estimated_hours = 40.0
                    
                    priority_val = row.get('优先级', row.get('priority', 1))
                    try:
                        priority = int(priority_val) if pd.notna(priority_val) else 1
                    except (ValueError, TypeError):
                        priority = 1
                    
                    task = Task(
                        task_id=str(row.get('任务编号', row.get('task_id', f'TSK{index:03d}'))).strip(),
                        project_id=str(row.get('项目编号', row.get('project_id', 'PRJ001'))).strip(),
                        task_name=str(row.get('任务名称', row.get('task_name', f'任务{index}'))).strip(),
                        estimated_hours=estimated_hours,
                        start_date=row.get('开始日期', row.get('start_date')),
                        end_date=row.get('结束日期', row.get('end_date')),
                        required_skills=required_skills,
                        priority=priority
                    )
                    tasks.append(task)
                except Exception as e:
                    self.logger.warning(f"跳过任务数据行 {index + 2}: {e}")
                    continue
            
            return tasks
            
        except Exception as e:
            self.logger.error(f"加载任务数据失败: {e}")
            return []
    
    def export_sample_template(self, output_path: str) -> None:
        """
        导出样例模板Excel文件
        
        Args:
            output_path (str): 输出文件路径
        """
        try:
            with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
                # 创建项目信息样例
                project_info_data = {
                    'project_code': ['PRJ001', 'PRJ002'],
                    'project_name': ['项目A', '项目B'],
                    'start_month': ['2024-01', '2024-03'],
                    'end_month': ['2024-06', '2024-08'],
                    'priority': [1, 2],
                    'description': ['项目A描述', '项目B描述']
                }
                pd.DataFrame(project_info_data).to_excel(
                    writer, sheet_name='project_info', index=False
                )
                
                # 创建项目角色样例
                project_roles_data = {
                    'project_code': ['PRJ001', 'PRJ001', 'PRJ002'],
                    'role_name': ['前端开发工程师', '后端开发工程师', '全栈开发工程师'],
                    'required_count': [2, 3, 2],
                    'skill_requirements': ['React,TypeScript', 'Java,Spring', 'Vue,Node.js'],
                    'experience_level': ['中级', '高级', '中级'],
                    'work_ratio': [1.0, 1.0, 0.8]
                }
                pd.DataFrame(project_roles_data).to_excel(
                    writer, sheet_name='project_roles', index=False
                )
                
                # 创建阶段详情样例
                phases_data = {
                    'project_code': ['PRJ001', 'PRJ001', 'PRJ002'],
                    'phase_name': ['需求分析', '开发实现', '系统设计'],
                    'start_month': ['2024-01', '2024-02', '2024-03'],
                    'end_month': ['2024-01', '2024-05', '2024-04'],
                    'dependencies': ['', '需求分析', ''],
                    'deliverables': ['需求文档', '系统代码', '设计文档'],
                    '前端开发工程师': [0, 2, 0],
                    '后端开发工程师': [0, 3, 0],
                    '全栈开发工程师': [0, 0, 2]
                }
                pd.DataFrame(phases_data).to_excel(
                    writer, sheet_name='phases_detail', index=False
                )
            
            self.logger.info(f"样例模板已导出到: {output_path}")
            
        except Exception as e:
            self.logger.error(f"导出样例模板失败: {e}")
            raise